/**
 * Created by scenic on 2017/6/26.
 */
var start, scene;
var cameraHelper;
var gsBuilder;



var meshGroup = new THREE.Group();
var debugDIV;
var rootSpaceArray = [];

function main() {
    var canvas = document.getElementById("canvas_3d");
    var container = document.getElementById("center_container");
    GSThree.CommonUtils.notNull(canvas);
    GSThree.CommonUtils.notNull(container);

    start = new GSThree.StartNB({canvas: canvas, container: container});
    scene = start.newScene("场景1");
    scene.sceneColor = "#0a0d19"

    new GSThree.LightConfig(scene).addAmbientLight().addDirectionLight();

    scene.add(meshGroup);
    meshGroup.name = "图形绘制";

    gsBuilder = GSResource;
    (function refresh() {
        requestAnimationFrame(refresh);
        start.renderMultipleScene();

        if (start.helperHightLight.object)
            start.selectedObject(start.helperHightLight.object);

        if (scene.lightConfig) {
            scene.lightConfig.updateHelper();
        }
    })()

    $(function () {
        $("#tabs_left").tabs();
    });

    $(function () {
        $("#tabs_right").tabs();
    });


    start.OnRePaintListener.addListener(function (scene, camera) {
        if (debugDIV == undefined) {
            debugDIV = document.getElementById("business_debug");
        }

        if (scene.translate.object) {
            var matrix = scene.translate.object.matrixWorld;
            var woldMatrix = GSThree.Utils.matrix4ToStringTable(matrix);
            var message = "world matrix";
            message += woldMatrix + "<br/>";
            message += "world rotation matrix" + "<br/>"
            message += GSThree.Utils.matrix4ToStringTable(new THREE.Matrix4().extractRotation(matrix));
            message += "world getInverse matrix" + "<br/>"
            message += GSThree.Utils.matrix4ToStringTable(new THREE.Matrix4().getInverse(matrix));

            message += "local matrix" + "<br/>"
            message += GSThree.Utils.matrix4ToStringTable(scene.translate.object.matrix);
            message += "local matrix rotation" + "<br/>"
            message += GSThree.Utils.matrix4ToStringTable(new THREE.Matrix4().extractRotation(scene.translate.object.matrix));
            debugDIV.innerHTML = message;
        }

    }, "debug-ui")
    start.OnRePaintListener.addListener(function (scene, camera) {
        if (scene.lightConfig && scene.lightConfig.directionalLight) {
            scene.lightConfig.directionalLight.position.copy(camera.position);
            if (scene.viewport.control.target) {
                scene.lightConfig.directionalLight.lookAt(scene.viewport.control.target);
            }
        }

    }, "fix-directional-light-change-with-camera")


    testDebug();
}

function testDebug() {
    var rootSpace = gsBuilder.SpaceUtils.createRootBoxSpace(1400,900,500);
    rootSpace.setSegment("1:1:1",new THREE.Vector3(1,0,0));
    rootSpace.updateSegment();
    rootSpace.children_space[0].setSegment("1:1:1",new THREE.Vector3(0,1,0));
    rootSpace.children_space[0].updateSegment();

    rootSpace.traverse(function () {
        this.addMeshToScene(scene)
    });
    rootSpaceArray.push(rootSpace);
    updateResource();

}

function onItemSelectedListener(object) {
    console.log(object);
    var object3d_property = document.getElementById("object3d_property");
    var business_property = document.getElementById("business_property");

    console.log(object3d_property);
    console.log(business_property);


    GSThree.CommonUtils.deleteDivElement(object3d_property);
    GSThree.CommonUtils.deleteDivElement(business_property);

    object3d_property.innerHTML = object.type == undefined ? "" : object.type;
    business_property.innerHTML = object.name;

    if (object instanceof THREE.PerspectiveCamera) {

        var fov = GSThree.CommonUtils.createSliderView("fov", function (value) {
            object.fov = parseFloat(value);
            object.updateProjectionMatrix();
        }, {value: object.fov})

        var zoom = GSThree.CommonUtils.createSliderView("zoom", function (value) {
            object.zoom = parseFloat(value);
            object.updateProjectionMatrix();
        }, {value: object.zoom})
        var focus = GSThree.CommonUtils.createSliderView("focus", function (value) {
            object.focus = parseFloat(value);
            object.updateProjectionMatrix();
        }, {value: object.focus})
        var aspect = GSThree.CommonUtils.createSliderView("aspect", function (value) {
            object.aspect = parseFloat(value);
            object.updateProjectionMatrix();
        }, {value: object.aspect})
        var filmGauge = GSThree.CommonUtils.createSliderView("filmGauge", function (value) {
            object.filmGauge = parseFloat(value);
            object.updateProjectionMatrix();
        }, {value: object.filmGauge})
        var filmOffset = GSThree.CommonUtils.createSliderView("filmOffset", function (value) {
            object.filmOffset = parseFloat(value);
            object.updateProjectionMatrix();
        }, {value: object.filmOffset})


        object3d_property.appendChild(fov);
        object3d_property.appendChild(zoom);
        object3d_property.appendChild(focus);
        object3d_property.appendChild(aspect);
        object3d_property.appendChild(filmGauge);
        object3d_property.appendChild(filmOffset);


    }
    if (object instanceof THREE.OrbitControls) {

    }
    if (object instanceof THREE.DirectionalLight) {
        scene.lightConfig.addDirectionLightHelper();
    }
    if (object instanceof THREE.Object3D) {
        scene.attachTranslate(object);
        var translator = Widget.createTranslator(object);
        object3d_property.appendChild(translator);
        object3d_property.appendChild(
            Widget.createCheckBox("Visible", object.visible, function (check) {
                object.setVisible(check);
            }));

    }
    if (object instanceof THREE.Mesh) {


    }
    if (object instanceof gsBuilder.Space) {

        var editText1 = Widget.createSlider(object.width, 100, 2000, function (value) {
            object.width = parseFloat(value);
            console.log("change finish the slide")
        })
        var editText2 = Widget.createSlider(object.height, 100, 2000, function (value) {
            object.height = parseFloat(value);
        })
        var editText3 = Widget.createSlider(object.depth, 100, 2000, function (value) {
            object.depth = parseFloat(value);
        })

        var segmentOrientation = new THREE.Vector3(1,0,0);
        var orientation = Widget.createCheckBoxRadio("title", ["横向", "竖直"], function (value) {
            console.log(value);
            if (value == '横向') {

            } else if (value == '竖直') {
                segmentOrientation = new THREE.Vector3(0,1,0);
            } else {
                console.error("can not match " + value)
            }
        });

        var segmentation = Widget.createEditText(object.segment, function (value) {
            object.setSegment(value, segmentOrientation);

            object.updateSegment();
            object.children_space.forEach(function (s) {
                scene.add(s.getAssociateMesh())
                s.getAssociateMesh.isAddToScene = true;
            })

            updateResource()

        })

        object3d_property.appendChild(editText1);
        object3d_property.appendChild(editText2);
        object3d_property.appendChild(editText3);
        object3d_property.appendChild(document.createTextNode("线性分割"));
        object3d_property.appendChild(segmentation);
        object3d_property.appendChild(orientation);

    }
    if (object instanceof gsBuilder.SpaceFace) {
        object.onClick(meshGroup);
        object.associatePlank.buildInteractive(object3d_property);
    }


    //有个选中态
    if ('getAssociateMesh' in object) {
        start.selectedObject(object.getAssociateMesh())
    }


}


function showEdgesHelper () {
    if (this.edgesShow == undefined) {
        this.edgesShow = false;
    }

    this.edgesShow = !this.edgesShow;
    GSThree.Utils.showEdgesHelper(scene, start, this.edgesShow);
}
function createRootSpace() {
    var rootSpace = gsBuilder.SpaceUtils.createRootBoxSpace(1400,900,500);
    rootSpace.addMeshToScene(scene);
    rootSpaceArray.push(rootSpace);
    updateResource();
}
function perspectiveView() {
    scene.viewport.changeCamera('p');
}
function topView() {
    var camera = scene.viewport.changeCamera('o');
    camera.position.set(0, 10000, 0);
    camera.rotation.set(-Math.PI / 2, 0, 0);
    scene.viewport.control.enableRotate = false;
}
function frontView() {
    var camera = scene.viewport.changeCamera('o');
    camera.position.set(0, 0, 10000);
    camera.rotation.set(0, 0, 0);
    scene.viewport.control.enableRotate = false;
}
function leftView() {
    var camera = scene.viewport.changeCamera('o');
    camera.position.set(-10000, 0, 0);
    camera.rotation.set(0, -Math.PI / 2, 0);
    scene.viewport.control.enableRotate = false;
}
function showCameraHelper() {
    var ss = undefined;
    start.scenes.forEach(function (s) {
        if (s.name == 'camera') {
            ss = s;
            return;
        }
    })

    if (cameraHelper != undefined) {
        start.scenes.deleteElementByValue(ss);
        ss.destroy();
        cameraHelper.destroy();
        cameraHelper = undefined;
    } else {
        cameraHelper = new GSThree.CameraHelper(start).showCameraHelper(scene);
    }


}
function updateResource() {
    gsBuilder.SpaceUtils.updateResource(rootSpaceArray[0])
}
function createBox() {
    var mesh1 = new GSThree.Mesh(new THREE.BoxBufferGeometry(100, 100, 100));
    scene.add(mesh1);

    var mesh2 = new GSThree.Mesh(new THREE.BoxBufferGeometry(50, 200, 50));

    mesh1.add(mesh2);

}
function spaceRefreshForce() {
    rootSpaceArray.forEach(function (rootSpace) {
        rootSpace.traverse(function (space) {
            space.needsUpdateMesh = true;

            space.needsUpdatePlank = true;
            space.needsUpdateSegment = true;
        })
    })
}
function showSpaceWithLine() {
    rootSpaceArray.forEach(function (rootSpace) {
        rootSpace.traverse(function (space) {
            GSThree.Utils.transparentMesh(space.getAssociateMesh(), true);
        })
    })
}
function randomEdgesLine() {
    scene.children.forEach(function (mesh) {
        if (mesh instanceof GSThree.HelperEdges) {
            mesh.setColor(Math.random() * 0xffffff)
        }
    })
}
function makeHole() {
    var DEBUG = true;
    if(DEBUG){
        console.log("make hole")
    }

    if(DEBUG){
        console.log("sideboard slot");
    }
    var space = rootSpaceArray[0];

    var leftPlank = space.leftFace;
    var rightPlank = space.rightFace;
    var backPlank = space.backFace;
    if(leftPlank && rightPlank && backPlank){

    }


}




